<template>
  <div class="rank">
    <div class="rank-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, Ref, computed, onUnmounted, getCurrentInstance } from "vue";
import { rank } from "@/types/rankType";
import useEchartsData from "@/store/useEchartsData";
import * as echarts from "echarts";
import throttleFn from "@/utils/throttle";
const store = useEchartsData();
//图表容器
let mychart: any;
//截取数据
let sliceRank: rank[] = [];
//按时循环数据结束索引
let end: Ref<number> = ref(11);
//定时器id
let timer: number;
//容器盒子
let container: HTMLElement;

// const proxy = getCurrentInstance()
// console.log(proxy?.appContext.config.globalProperties);

const rankList = computed(() => {
  return store.rankList;
});



//获取数据
// const getData = (result: any) => {
//   console.log(1);

//   console.log(result);
// }
// proxy?.appContext.config.globalProperties.$socket.send({
//   action: 'getData',
//   socketType: 'rankData',
//   chartName: 'rank',
//   value: ''
// })
// proxy?.appContext.config.globalProperties.$socket.registerCallBack('rankData', getData)

//初始化图表
const initChart = () => {
  mychart = echarts.init(
    document.querySelector(".rank-container") as HTMLElement,
    "dark-blue"
  );

  let option = {
    title: {
      top: "5%",
      left: "5%",
      text: "(❁´◡`❁)商家销量排行",
      textStyle: {
        fontSize: (container.offsetWidth / 100) * 2,
      },
    },
    xAxis: {
      type: "category",
    },
    yAxis: {
      type: "value",
      name: "销售金额(万)",
    },
    grid: {
      top: "30%",
      left: "5%",
      bottom: "5%",
      right: "5%",
    },
    tooltip: {
      trigger: "axis",

      axisPointer: {
        type: "shadow",
        axis: "auto",
      },
    },
    series: [
      {
        type: "bar",
        barWidth: 60,
        itemStyle: {
          borderRadius: [33, 33, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            {
              offset: 0,
              color: "#5052ee",
            },
            {
              offset: 1,
              color: "#ab6ee5",
            },
          ]),
        },
      },
    ],
  };
  mychart.setOption(option);

  mychart.on("mouseover", stopInterver);
  mychart.on("mouseout", startInterver);
};

//更新图表数据
const upDateChart = () => {

  let seriesData = sliceRank.map((item) => {
    return item.value;
  });

  let xName = sliceRank.map((item) => {
    return item.name;
  });

  let rankValueList = rankList.value.map((item) => Number(item.value));
  let newOption = {
    xAxis: {
      data: xName,
    },
    yAxis: {
      max: Math.max(...rankValueList),
      min: 0,
      interval: Math.ceil((Math.max(...rankValueList) - 0) / 6),
    },
    series: [
      {
        data: seriesData,
      },
    ],
  };

  mychart.setOption(newOption);
};

//动态渲染图表数据
const applyChart = () => {
  timer = setInterval(() => {
    end.value++;
    end.value > 20 ? (end.value = 0) : end.value;

    let item = rankList.value[end.value];
    // console.log(end.value, rankList.value[end.value]);

    sliceRank.shift();
    sliceRank.push(item);
    // console.log(sliceRank);

    //更新图表
    upDateChart();
  }, 1500);
};

//鼠标进入停止定时器
const stopInterver = () => {
  clearInterval(timer);
};

//开始定时器
const startInterver = () => {
  applyChart();
};

//自适应尺寸函数
const resizeFn = () => {
  return throttleFn(function () {
    let resizeOption = {
      title: {
        textStyle: {
          fontSize: (container.offsetWidth / 100) * 2,
        },
      },
    };

    mychart.setOption(resizeOption);
    mychart.resize();
  }, 100);
};

store.$subscribe((mutations, state) => {
  sliceRank = state.rankList.slice(0, 11);
});

onMounted(async () => {
  try {
    await store.getRankData();
  } catch (error) {
    console.log(error);
  }

  container = document.querySelector(".rank-container") as HTMLElement;


  //初始化图表
  initChart();
  //配置图表
  upDateChart();
  //动态改变数据
  applyChart();

  //图表自适应尺寸
  window.addEventListener("resize", resizeFn());
});

onUnmounted(() => {
  //清理定时器
  clearInterval(timer);
});
</script>

<script lang="ts">
// export default {
//   data() {
//     return {
//       num1: this.$axios
//     }
//   },
// }
</script>

<style lang="less" scoped>
.rank {
  width: 100%;
  height: 100%;

  .rank-container {
    width: 100%;
    height: 100%;
  }
}
</style>
